<template>
  <!-- 地图 -->
  <div class="container" style="padding: 0px">
    <div id="map3D"></div>
    <!-- 控制按钮组 -->
    <ul class="btn-wrap">
      <li class="btn" @click="startAnimation">开始</li>
      <li class="btn" @click="pauseAnimation">暂停</li>
      <li class="btn" @click="resumeAnimation">继续</li>
      <li class="btn" @click="stopAnimation">重置</li>
    </ul>
  </div>
</template>

<script>
import { newMap3D } from "@/common/js/map3D.js";
export default {
  data () {
    return {
      map: null,
      mapZoom: 20,
      trackAni: null, // 轨迹动画实例
      // 轨迹路径点坐标
      path: [
        { Lng: 116.297611, Lat: 40.047363 },
        { Lng: 116.302839, Lat: 40.048219 },
        { Lng: 116.308301, Lat: 40.050566 },
        { Lng: 116.305732, Lat: 40.054957 },
        { Lng: 116.304754, Lat: 40.057953 },
        { Lng: 116.306487, Lat: 40.058312 },
        { Lng: 116.307223, Lat: 40.056379 }
      ],
      formTrack: {
        line: null,
      }
    }
  },
  mounted () {
    // 显示地图  
    this.mapShow()
    // this.getPlaybackData()
  },
  beforeDestroy () {
    // 销毁地图实例，释放资源
    if (this.map) {
      this.map.destroy()
    }
    // 停止动画
    if (this.trackAni) {
      this.trackAni.stop()
    }2
  },
  methods: {
    // 显示地图
    mapShow () {
      this.map = newMap3D();
      
      // this.buildTrack(this.path)
      this.getPlaybackData()
    },
    buildTrack (data) {
      this.map.centerAndZoom(new BMapGL.Point(data[0].Lng, data[0].Lat), 21);
      this.map.setHeading(-78); //设置地图旋转角度
      this.map.setTilt(70); //设置地图的倾斜角度

      var track = new Track.View(this.map, {
        lineLayerOptions: {
          style: {
            strokeWeight: 8,
            strokeLineJoin: 'round',
            strokeLineCap: 'round'
          }
        }
      });

      var trackData = [];
      var colorOffset = [];
      data.forEach(item => {
        var point = new BMapGL.Point(item.Lng, item.Lat);
        var trackPoint = new Track.TrackPoint(point);
        trackData.push(trackPoint);
        var choose = [0.9, 0.5, 0.1];
        var color = choose[Math.floor(Math.random() * choose.length)];
        colorOffset.push(color);
      });

      var trackLine = new Track.LocalTrack({
        trackPath: trackData,
        duration: 20, // 60
        style: {
          sequence: true,
          marginLength: 32,
          arrowColor: '#fff',
          strokeTextureUrl: 'http://mapopen-pub-jsapi.bj.bcebos.com/jsapiGlgeo/img/down.png',
          strokeTextureWidth: 64,
          strokeTextureHeight: 32,
          traceColor: [27, 142, 236]
        },
        linearTexture: [[0, '#f45e0c'], [0.5, '#f6cd0e'], [1, '#2ad61d']],
        gradientColor: colorOffset
      });
      this.formTrack.line = trackLine;

      let that = this;
      trackLine.on(Track.LineCodes.STATUS, (status) => {
        switch (status) {
          case Track.StatusCodes.PLAY:
          case Track.StatusCodes.RESUME:
            break;
          case Track.StatusCodes.INIT:
          case Track.StatusCodes.PAUSE:
          case Track.StatusCodes.STOP:
          case Track.StatusCodes.FINISH:
            var box = trackLine.getBBox();
            if (box) {
              var bounds = [new BMapGL.Point(box[0], box[1]), new BMapGL.Point(box[2], box[3])];
              that.map.setViewport(bounds);
            }
            break;
          default:
            break;
        }
      });

      track.addTrackLine(trackLine);
      track.focusTrack(trackLine);

      var movePoint = new Track.GroundPoint({
        point: trackData[0].getPoint(),
        style: {
          url: 'http://mapopen-pub-jsapi.bj.bcebos.com/jsapiGlgeo/img/car.png',
          level: 18,
          scale: 1,
          size: new BMapGL.Size(16, 32),
          anchor: new BMapGL.Size(0.5, 0.5),
        }
      });
      movePoint.addEventListener(Track.MapCodes.CLICK, (e) => {
        console.log('Track.GroundPoint.click', e);
      })
      movePoint.addEventListener(Track.MapCodes.MOUSE_OVER, (e) => {
        console.log('Track.GroundPoint.MOUSE_OVER', e);
      })
      movePoint.addEventListener(Track.MapCodes.MOUSE_OUT, (e) => {
        console.log('Track.GroundPoint.MOUSE_OUT', e);
      })
      trackLine.setMovePoint(movePoint);

    },
    /**
     * 开始动画
     */
    startAnimation () {
      this.formTrack.line.startAnimation()
    },

    /**
     * 暂停动画
     */
    pauseAnimation () {
      this.formTrack.line.pauseAnimation()
    },

    /**
     * 继续动画
     */
    resumeAnimation () {
      this.formTrack.line.resumeAnimation()
    },

    /**
     * 停止动画
     */
    stopAnimation () {
      this.formTrack.line.stopAnimation()
      this.map.setHeading(-78);
      this.map.setTilt(70);
      this.map.setZoom(21);
    },
    // 获取车辆轨迹
    async getPlaybackData () {
      var url = 'http://111.160.78.62:9930/Cityscapeapi/DataListCompany/GetVehicleHistoryInfoListApi?VID=19228&startTime=2025-8-20+00:00:00&endTime=2025-8-20+09:59:59'
      let { data } = await this.$Http.get(url)

      // 方法一
      // 转换路径点为BMapGL.Point数组
      // const points = data.map(point =>
      //   new BMapGL.Point(point.Lng, point.Lat)
      // )

      // setTimeout(() => this.startAnimation1(points), 3000)

      // 方法二
      this.buildTrack(data)
    },
    /**
     * 启动轨迹动画
     */
    startAnimation1 (points) {
      // 创建折线对象
      var polyline = new BMapGL.Polyline(points, {
        strokeColor: '#1E90FF', // 线条颜色
        strokeWeight: 5, // 线条宽度
        strokeOpacity: 0.8 // 线条透明度
      })
      // 添加折线到地图
      this.map.addOverlay(polyline)
      // 创建轨迹动画实例
      this.trackAni = new BMapGLLib.TrackAnimation(this.map, polyline, {
        overallView: true, // 动画过程中是否自动调整视野
        tilt: 73, // 倾斜角度
        zoom: 20, // 地图缩放比例
        duration: 20000, // 动画持续时间（毫秒）
        delay: 300 // 动画开始延迟时间（毫秒）
      })
      // 启动动画
      this.trackAni.start()
    },
    // 获取垃圾点位
    async getRubbishPointCCApi () {
      var url = 'http://111.160.78.62:9930/Cityscapeapi/RubbishVehicle/GetRubbishHistoryCCApi?CLIENT_NO=0000019&WORKDATE=2025-8-20&TYPE=0'
      let { data } = await this.$Http.get(url)
      this.map.centerAndZoom(new BMapGL.Point(data[0].经度, data[0].纬度), 21);

      this.drawPoint(data)
    },
    // 展示垃圾点位
    drawPoint (arrayDataForSameIcon) {
      var view = new mapvgl.View({
        map: this.map,
      });
      const _self = this;
      let img = new Image();
      img.src = require("@/assets/img/marker/rubbishMarker1.png");
      img.onload = function () {
        let arrayImage = arrayDataForSameIcon.map((v) => {
          v.geometry = {
            type: "Point",
            coordinates: [v.经度, v.纬度],
          };
          v.icon = img;
          v.text = v.垃圾点名称;
          return v;
        });
        let optionsICON = {
          draw: "icon",
          width: 30, // 规定图像的宽度
          height: 38, // 规定图像的高度
        };
        var mapvglIcon = new mapvgl.IconLayer({
          width: 30,
          height: 38,
          icon: optionsICON,
        });
        view.addLayer(mapvglIcon);
        mapvglIcon.setData(arrayImage);
      }
    },
  },
}
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  #map3D {
    height: 100%;
  }
}
ul li {
  list-style: none;
}

.btn-wrap {
  z-index: 999;
  position: fixed;
  bottom: 3.5rem;
  margin-left: 3rem;
  padding: 1rem 1rem;
  border-radius: 0.25rem;
  background-color: #fff;
  box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}

.btn {
  width: 75px;
  height: 30px;
  float: left;
  background-color: #fff;
  color: rgba(27, 142, 236, 1);
  font-size: 14px;
  border: 1px solid rgba(27, 142, 236, 1);
  border-radius: 5px;
  margin: 0 5px;
  text-align: center;
  line-height: 30px;
}

.btn:hover {
  background-color: rgba(27, 142, 236, 0.8);
  color: #fff;
}
</style>
